<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isreFreshloading"
      :success-text="refreshSuccessText"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ArticleItem v-for="(article) in list" :key="article.art_id" :article="article"></ArticleItem>
        <van-cell v-for="(article,index) in list" :key="index" :title="article.title" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article";
import ArticleItem from "@/components/article-item/index.vue";
export default {
  name: "ArticleList",
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [], //存储连败哦数据的数组
      loading: false, //控制加载中loading状态
      finished: false, //控制数据加载结束的状态
      timestamp: null, //请求获取下一页数据的时间戳
      error: false, //控制列表加载失败的状态提示
      isreFreshloading: false, //控制下拉刷新的状态
      refreshSuccessText: "刷新成功" //下拉刷新成功提示文本
    };
  },
  methods: {
    async onLoad() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        });
        console.log(data);
        //人为的制造错误
        // if (Math.random() > 0.5) {
        //   JSON.parse('aklshdashdk')
        // }
        const { results } = data.data;
        // 数组的展开操作符
        this.list.push(...results);
        console.log(this.list);

        this.loading = false;

        // console.log(data);
        if (results.length) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (err) {
        this.error = false;
        this.loading = false;
        console.log("请求失败", err);
        this.$toast("请求失败");
      }
    },
    //当下拉刷新的时候会触发调用该函数
    async onRefresh() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id, //频道id
          timestamp: Date.now(), //下拉刷新每次获取最新数据
          with_top: 1 //是否包含置顶，进入页面第一次请求是要包含置顶
        });
        //将数据追加到列表的顶部
        const { results } = data.data;
        this.list = results;
        console.log(results);
        //关闭下拉刷新的 loading状态
        this.isreFreshloading = false;
        //更新下拉刷新成功提示的文本
        this.refreshSuccessText = `刷新成功,更新了${results.length}条数据`;
      } catch (err) {
        console.log("请求失败1", error);
      }
    }
  }
};
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>